/*
 * $Id: Hashable.hpp 120 2011-03-02 07:02:52Z hyunghwan.chung $
 *
   Copyright 2005-2009 Chung, Hyung-Hwan.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an  BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

#ifndef _XP_HASHABLE_CLASS_
#define _XP_HASHABLE_CLASS_

#include <xp/types.h>
#include <xp/macros.h>

XP_BEGIN_NAMESPACE (xp)

class Hashable
{
public:
	virtual ~Hashable () {}

	virtual xp_size_t hashCode () const = 0;

	static xp_size_t hashCode (xp_size_t init, const xp_char_t* str)
	{
		xp_size_t n = init;

		while (*str != XP_T('\0'))
		{
			const xp_byte_t* p = (const xp_byte_t*)str;
			for (xp_size_t i = 0; i < XP_SIZEOF(*str); i++)
				n = n * 31 + *p++;	
			str++;
		}

		return n;
	}

	static xp_size_t hashCode (const xp_char_t* str)
	{
		return hashCode (0, str);
	}

	static xp_size_t hashCode (xp_size_t init, const void* data, xp_size_t size)
	{
		xp_size_t n = init;
		const xp_byte_t* p = (const xp_byte_t*)data;

		/*
		for (xp_size_t i = 0; i < size; i++) {
			n <<= 1;
			n += *p++;
		}
		*/

		for (xp_size_t i = 0; i < size; i++) n = n * 31 + *p++;

		/*
		for (xp_size_t i = 0; i < size; i++) {
			n = (n << 4) + *p++;
			//xp_size_t g = n & 0xF0000000U;
			xp_size_t g = n & ((xp_size_t)0xF << (xp_sizeof(xp_size_t) * 8 - 4));
			n &= ~g;
		}
		*/

		return n;
	}

	static xp_size_t hashCode (const void* data, xp_size_t size)
	{
		return hashCode (0, data, size);
	}

};

XP_END_NAMESPACE (xp)

#endif
